﻿using DevExpress.DataAccess.ObjectBinding;
using DevExpress.XtraReports.UI;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.BusinessObjects.Managements.StoreServices;
using YAPACS.RisServer.Abstractions;

namespace YAPACS.RisServer.Services;

public class ReportPdfService : DomainService, IReportPdfService
{
    private readonly IReportStyleService _reportStyleService;
    private readonly IRepository<Report, Guid> _reportRepository;

    public ReportPdfService(IReportStyleService reportStyleService, IRepository<Report, Guid> reportRepository)
    {
        _reportStyleService = reportStyleService;
        _reportRepository = reportRepository;
    }

    public async Task<bool> GeneratePdfFileAsync(Guid reportId, ReportStyleType reportStyleType)
    {
        var report = await _reportRepository.GetAsync(reportId);
        return await GeneratePdfFileAsync(report, reportStyleType);
    }

    public async Task<bool> GeneratePdfFileAsync(Report report, ReportStyleType reportStyleType)
    {
        ReportStyle reportStyle = null;

        if (reportStyleType == ReportStyleType.TempReport)
        {
            var tempReportStyle = await _reportStyleService.GetTempReportStyleAsync(report);
            if (tempReportStyle != null)
            {
                reportStyle = tempReportStyle;
            }
        }

        reportStyle ??= await _reportStyleService.GetReportStyleAsync(report);

        if (reportStyle != null && reportStyle.Content.Length > 0)
        {
            using var xtraReport = new XtraReport();
            xtraReport.ApplyLocalization("zh-Hans");
            using var stream = new MemoryStream(reportStyle.Content);
            xtraReport.LoadLayout(stream);
            xtraReport.DataSource = new ObjectDataSource { DataSource = report.Exam };
            using var pdfStream = new MemoryStream();
            await xtraReport.ExportToPdfAsync(pdfStream);
            pdfStream.Seek(0, SeekOrigin.Begin);
            var container = report.Exam.StoreService.GetBlobContainer();
            await container.SaveAsync(report.ReportFile, pdfStream, true);

            return true;
        }

        return false;
    }

    public async Task<bool> DeletePdfFileAsync(Report report)
    {
        var container = report.Exam.StoreService.GetBlobContainer();
        return await container.DeleteAsync(report.ReportFile);
    }
}
